import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
import Register from './views/Register.vue'

Vue.use(Router)

const router = new Router({
    routes: [
        {
            path: '/',
            name: 'home',
            component: Home,
            meta: { requiresAuth: true }
        },
        {
            path: '/login',
            name: 'login',
            component: Login,
            meta: { guestOnly: true }
        },
        {
            path: '/register',
            name: 'register',
            component: Register,
            meta: { guestOnly: true }
        },
        {
            path: '/user/:userId',
            name: 'user',
            component: () => import('./views/UserDetail.vue'),
            meta: { requiresAuth: true }
        }
    ]
})

router.beforeEach((to, from, next) => {
    const isAuthenticated = router.app.$store.getters['auth/isAuthenticated']

    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login')
    } else if (to.meta.guestOnly && isAuthenticated) {
        next('/')
    } else {
        next()
    }
})

export default router